/*
 * @Author: yangrongxin
 * @Date: 2021-07-26 17:06:17
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:28:15
 */
import { useState, useEffect } from 'react';
import { View, Text, Button, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { AtIcon } from 'taro-ui';
import { connect } from 'react-redux';
import styles from './index.module.less';
import PickerWapper from '@/components/PickerWapper';
import { getItemSync, setItemSync } from '@/utils/storage';
import { STORAGE_TYPE } from '@/const/dataDictionary';
import { serviceList } from '@/const/config';

// const loginIcon = 'https://hxgywx.oss-cn-shenzhen.aliyuncs.com/nursing-customer/assets/login.png';
const loginIcon = 'https://hxgywx.oss-cn-shenzhen.aliyuncs.com/hxt-wxminiprogram/logo.png';

const envList = ['dev', 'test', 'staging', 'production'];
const Login = (props: any) => {
  const { dispatch } = props;

  const [isAcceptAgreement, setIsAcceptAgreement] = useState<boolean>(false);
  const [loginCode, setLoginCode] = useState('');
  const [loading, setLoading] = useState(false);
  // 切换当前环境的方法
  const defaultEnv = SHOW_TEST_TOOLS === 'true' && getItemSync(STORAGE_TYPE.DEBUGGER_HOST)?.MINI_PROGRAM_STATE_ENV;
  const [currentService, setCurService] = useState<string>(defaultEnv || MINI_PROGRAM_STATE_ENV);
  const [servicePanelOpen, setServicePanelOpen] = useState<boolean>(false);

  useEffect(() => {
    Taro.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#f7f6ff',
    });
    loginGetCode();
  }, []);

  const loginGetCode = () => {
    Taro.login().then(({ code }) => {
      setLoginCode(code);
    });
  };

  const onGetPhoneNumber = (e) => {
    const {
      detail: { errMsg = '', iv = '', encryptedData = '' },
    } = e;
    setLoading(true);
    // 增加游客流程 登录的时候 获取code进行登录
    dispatch({
      type: 'global/loginWithUserPhone',
      payload: {
        channelCode: API_CHANNELCODE,
        encrypted: encryptedData,
        iv,
        loginDeviceNum: `${new Date().getTime()}`,
        loginDeviceType: 'WX_APP',
        organCode: 'HXTAPP',
        weChatRequestType: 'MINI_PROGRAM',
        code: loginCode,
      },
      callback: () => {
        setLoading(false);
        loginGetCode();
      },
    });
  };

  const onClickAgreement = () => {
    setIsAcceptAgreement(!isAcceptAgreement);
  };

  /**
   * 跳转查看服务协议
   */
  const readAgreement = () => {
    Taro.navigateTo({
      url: '/pages/ReadAgreement/index?textCode=hxt_wxapp_user_agreement',
    });
  };

  return (
    <View className={styles.container}>
      <Image className={styles.logoImg} src={loginIcon} />
      <View className={styles.text1}>请点击微信快捷登录</View>
      <View className={styles.text2}>才能享受我们为您提供的心理测评服务</View>
      <Button
        className={styles.quickLogin}
        open-type="getPhoneNumber"
        disabled={!isAcceptAgreement}
        loading={loading}
        onGetPhoneNumber={onGetPhoneNumber}
      >
        <Text>微信快捷登录</Text>
      </Button>
      {/* 测试当前按钮获取会员信息 */}
      <View className={styles.agreement}>
        <AtIcon
          onClick={onClickAgreement}
          // prefixClass="icon"
          value="check-circle"
          size="20"
          color={isAcceptAgreement ? '#F57878' : '#ccc'}
        ></AtIcon>
        <Text>勾选即代表同意</Text>
        <Text onClick={readAgreement}>《服务协议》</Text>
      </View>
      {SHOW_TEST_TOOLS === 'true' && (
        <View className={styles.menu_item} onClick={() => setServicePanelOpen(true)}>
          <Text>当前环境：{currentService}</Text>
        </View>
      )}
      <PickerWapper
        title="请选择当前运行环境"
        rangeList={envList}
        isOpened={servicePanelOpen}
        indexValue={envList.indexOf(currentService)}
        onClose={() => setServicePanelOpen(false)}
        onChange={(val: string) => {
          setCurService(val);
          setItemSync(STORAGE_TYPE.DEBUGGER_HOST, serviceList[val]);
          setServicePanelOpen(false);
        }}
      />
    </View>
    // <Button open-type="getPhoneNumber" onGetPhoneNumber={onGetPhoneNumber}>
    //   点击进行登录
    // </Button>
  );
};

export default connect(({ global }) => ({ ...global }))(Login);
